<template>
  <!-- 目标完成情况 -->

  <a-form-model ref="ruleForm" :model="keyrateVO" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
    <!-- 表单 -->
    <div class="flex-row">
      <title-name title="关键绩效指标完成情况"></title-name>
      <a-button @click="handerTable">全屏查看表格</a-button>
    </div>

    <s-table
      bordered
      :scroll="{ x: 3000 }"
      ref="table"
      rowKey="key"
      :page-keys="['pageNum', 'pageSize']"
      tableLayout="fixed"
      size="default"
      :columns="columns"
      :data="loadData"
      :alert="true"
      :rowClassName="(record, index) => (record.branchCompanyName === record.projectName ? 'table-striped' : null)"
      show-size-changer
      show-quick-jumper
      :showPagination="false"
    >
      <template slot="action" slot-scope="text, record">
        <a v-if="record.type === 1" @click="handleManage(0, record)">查看</a>
        <span v-else>-</span>
      </template>
      <template slot="haveRank" slot-scope="text, record">
        <span v-if="record.haveRank == null">-</span>
        <a-switch v-else :disabled="editModel == 0" v-model="record.haveRank" @click="handerHaveRank" />
      </template>
      <template slot="auditStatus" slot-scope="text, record">
        <list-status :status="record.auditStatus" :isApproval="true" conversion="en" :text="text"></list-status>
      </template>
    </s-table>
    <!-- <div class="del_btn mb12">*关键指标中红色的指标为项目部已申请不参加考核的指标。</div> -->
    <a-tabs class="mt12" :activeKey="currentStep" @change="callback">
      <a-tab-pane key="1" tab="风险情况统计">
        <s-table
          :scroll="{ x: 2400 }"
          bordered
          ref="risk"
          tableLayout="fixed"
          size="default"
          rowKey="projectId"
          :columns="riskStatisticsColumns"
          :data="riskStatisticsData"
          :alert="true"
          show-size-changer
          show-quick-jumper
          :showPagination="false"
        >
          <template v-for="col in ['takeSteps', 'complete', 'branchCompanyDutyId', 'projectDutyId', 'endTime', 'remarks']" :slot="col" slot-scope="text, record">
            <div :key="col" class="form-item">
              <BaseTextarea v-if="col === 'analysis' || col == 'takeSteps'" v-model="record[col]" :maxLength="1000" :disabled="editModel == 0" />
              <ASelectOrgPeople v-if="col === 'branchCompanyDutyId'" :disabled="editModel == 0" :init="false" :form="keyrateVO" key-value="branchCompanyOrgId" option-key="id" v-model="record[col]"></ASelectOrgPeople>
              <ASelectOrgPeople v-if="col === 'projectDutyId'" :disabled="editModel == 0" :init="false" :form="keyrateVO" key-value="projectOrgId" option-key="id" v-model="record[col]"></ASelectOrgPeople>
              <a-select v-if="col === 'complete'" v-model="record[col]" :disabled="editModel == 0">
                <a-select-option value="1"> 是 </a-select-option>
                <a-select-option value="0"> 否 </a-select-option>
              </a-select>
              <a-date-picker v-if="col === 'endTime'" v-model="record[col]" :disabled="editModel == 0" placeholder="请选择" value-format="YYYY-MM-DD" />
              <BaseTextarea :maxLength="1000" v-if="col === 'remarks'" :class="col === 'remarks' ? 'remark' : ''" v-model="record[col]" :disabled="editModel == 0" />
            </div>
          </template>
          <template slot="action" slot-scope="text, record">
            <a-popconfirm
              title="确定要删除?"
              @confirm="
                record.isDeleted = 1
                $refs.risk.refresh()
              "
            >
              <a :disabled="editModel == 0 || record.isDeleted == 1">删除</a>
            </a-popconfirm>
          </template>
        </s-table>
      </a-tab-pane>
      <a-tab-pane forceRender key="2" tab="影响履约重大事项">
        <s-table
          bordered
          ref="important"
          tableLayout="fixed"
          size="default"
          rowKey="projectId"
          :columns="importantMattersColumns"
          :data="importantMattersData"
          :alert="true"
          show-size-changer
          show-quick-jumper
          :showPagination="false"
        >
          <template v-for="col in ['designProblem', 'subProblem', 'other']" :slot="col" slot-scope="text, record">
            <div :key="col" class="form-item">
              <BaseTextarea v-if="col != 'other'" v-model="record[col]" :maxLength="1000" :disabled="editModel == 0" />
              <BaseTextarea v-else :maxLength="1000" :class="col === 'other' ? 'remark' : ''" v-model="record[col]" :disabled="editModel == 0" />
            </div>
          </template>
          <template slot="action" slot-scope="text, record">
            <a-popconfirm
              title="确定要删除?"
              @confirm="
                record.isDeleted = 1
                $refs.important.refresh()
              "
            >
              <a :disabled="editModel == 0 || record.isDeleted == 1">删除</a>
            </a-popconfirm>
          </template>
        </s-table>
      </a-tab-pane>
      <a-tab-pane forceRender key="3" tab="投诉">
        <s-table
          bordered
          ref="complaints"
          tableLayout="fixed"
          size="default"
          rowKey="projectId"
          :columns="complaintsColumns"
          :data="complaintsData"
          :alert="true"
          show-size-changer
          show-quick-jumper
          :showPagination="false"
        >
          <template v-for="col in ['complaint']" :slot="col" slot-scope="text, record">
            <div :key="col" class="form-item">
              <BaseTextarea v-model="record[col]" :maxLength="1000" :disabled="editModel == 0" />
            </div>
          </template>
          <template slot="action" slot-scope="text, record">
            <a-popconfirm
              title="确定要删除?"
              @confirm="
                record.isDeleted = 1
                $refs.complaints.refresh()
              "
            >
              <a :disabled="editModel == 0 || record.isDeleted == 1">删除</a>
            </a-popconfirm>
          </template></s-table
        >
      </a-tab-pane>
    </a-tabs>
    <title-name class="mt12" title="业主确认延期佐证资料" style="margin-top:20px"></title-name>
    <SupportingInformationFile :data="form.owerFileDTOList" />
    <!-- 页脚操作栏 -->
    <div class="btn_box tool-btns--fixed" style="bottom: 50px" v-if="editModel != 0">
      <a-button class="button_right" type="primary" @click="() => $emit('previousStep')">上一步</a-button>
      <a-button type="primary" @click="() => $emit('nextStep')">下一步</a-button>
    </div>
  </a-form-model>
</template>

<script>
import { api } from '@/api/project/performanceAnalysis'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BSelect from '@/components/BComponents/BSelect'
import { targetComplete, riskStatisticsColumns, importantMattersColumns, complaintsColumns } from '../model.js'
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'

import SupportingInformationFile from '../../branchPerformanceAnalysis/components/SupportingInformationFile'

export default {
  name: 'targetComplete',
  extends: new BaseEditPage(),
  components: {
    BSelect,
    ASelectOrgPeople,
    SupportingInformationFile
  },

  data() {
    this.columns = targetComplete
    this.riskStatisticsColumns = riskStatisticsColumns
    this.importantMattersColumns = importantMattersColumns
    this.complaintsColumns = complaintsColumns
    return {
      loading: false, // 加载控件
      editModel: 1, // 操作状态:0 查看;1 编辑

      id: '',
      currentStep: '1',
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      keyrateVO: { riskDTOList: [], majorDTOList: {}, complaintDTOList: [], keyrateDTOList: [] },
      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.keyrateVO.keyrateDTOList || []
          })
        })
      },
      riskStatisticsData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.keyrateVO.riskDTOList.filter((i) => !i.isDeleted) || []
          })
        })
      },
      importantMattersData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.keyrateVO.majorDTOList.filter((i) => !i.isDeleted) || []
          })
        })
      },
      complaintsData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.keyrateVO.complaintDTOList.filter((i) => !i.isDeleted) || []
          })
        })
      }
    }
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    },
    form: {
      type: Object,
      default: {}
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            this.editModel = 0
          })
        }
      }
    },
    // 对《关键绩效指标》完成情况合并项进行处理
    'keyrateVO.keyrateDTOList': {
      deep: true,
      handler(e) {
        e.length && this.handleMerge(e, true)
      }
    },
    // // 对《风险情况统计》合并项进行处理
    'keyrateVO.riskDTOList': {
      deep: true,
      handler(e) {
        console.log(e)
        e.length && this.handleMerge(e)
      }
    },
    // 对《影响履约重大事项》合并项进行处理
    'keyrateVO.majorDTOList': {
      deep: true,
      handler(e) {
        e.length && this.handleMerge(e)
      }
    },
    // 对《投诉》合并项进行处理
    'keyrateVO.complaintDTOList': {
      deep: true,
      handler(e) {
        e.length && this.handleMerge(e)
      }
    }
  },

  mounted() {
    // 不为添加时请求详情
    this.keyrateVO = this.form.keyrateVO
    let list = this.form.companyVO.month.split('-'),
      month = ''
    month = parseInt(list[1])
    this.riskStatisticsColumns[4].title = month - 1 + '月滞后天数'
    this.riskStatisticsColumns[5].title = month + '月滞后天数'
    this.riskStatisticsColumns[6].title = month + '月工期履约率'
    this.keyrateVO.riskDTOList = this.keyrateVO.riskDTOList || []
    this.$nextTick(() => {
      this.$refs.risk.refresh(true)
      this.$refs.important.refresh(true)
      this.$refs.complaints?.refresh(true)
      setTimeout(() => {
        this.$refs.risk.$children[0]?.$children[0]?.$children[0]?.$children[0]?.$children[0]?.$children[0].syncFixedTableRowHeight()
        this.$refs.important.$children[0]?.$children[0]?.$children[0]?.$children[0]?.$children[0]?.$children[0].syncFixedTableRowHeight()
        this.$refs.complaints.$children[0]?.$children[0]?.$children[0]?.$children[0]?.$children[0]?.$children[0].syncFixedTableRowHeight()
      })
      this.$refs.table.refresh(true)
    })
  },

  methods: {
    /**
     * @description: 合并处理
     * @param {Array} datas: 列表
     * @param {Boolean} needMergeCol: 是否合并列
     */
    handleMerge(datas, needMergeCol) {
      let list = datas?.filter((i) => !i.isDeleted)
      list.forEach((item, index) => {
        item.key = index
        // 合并分公司相同的行
        if (item.branchCompanyName !== list[index - 1]?.branchCompanyName && item.branchCompanyName === list[index + 1]?.branchCompanyName) {
          item.rowSpan = list.filter((i) => i.branchCompanyName === item.branchCompanyName).length
        } else if (item.branchCompanyName === list[index - 1]?.branchCompanyName) {
          item.rowSpan = 0
        } else if (item.rowSpan || item.rowSpan === 0) {
          item.rowSpan = 1
        }
        // 合并项目和分公司相同的列
        if (needMergeCol && item.projectName === item.branchCompanyName) {
          item.colSpan = 2
        }
      })
    },
    handerHaveRank() {
      this.$refs.table.localLoading = true
      api
        .updateTableSwicthCom(this.keyrateVO)
        .then((res) => {
          if (res.code == 200) {
            this.keyrateVO.keyrateDTOList = res.data
            // 对《关键绩效指标》完成情况合并项进行处理
            this.keyrateVO.keyrateDTOList.length && this.handleMerge(this.keyrateVO.keyrateDTOList, true)
            this.$refs.table.refresh(true)
          }
        })
        .finally(() => {
          this.$refs.table.localLoading = false
        })
    },
    // 操作栏
    async handleManage(type, record) {
      let query = {
        editModel: type
      }
      if (record?.dataId) {
        query.id = record.dataId
      }
      this.$router.push({
        name: 'updateProjectPerformanceAnalysis',
        query
      })
    },
    handerTable() {
      const query = {
        id: this.id
      }
      const routeData = this.$router.resolve({
        path: '/screenTableCom',
        query
      })
      window.open(routeData.href, '_blank')
    },
    callback(step) {
      this.currentStep = step
    },
    updateList() {
      api.updateTableList(this.keyrateVO.keyrateDTOList).then((res) => {
        if (res.code == 200) {
          this.keyrateVO.keyrateDTOList = res.data
          this.$refs.table.refresh(true)
        }
      })
    },
    delItem(index) {
      this.keyrateVO.riskDTOList.splice(index, 1)
      this.$refs.risk.refresh()
    },
    addRisk() {
      this.keyrateVO.riskDTOList.push({
        analysis: '',
        takeSteps: '',
        complete: '0',
        branchCompanyDutyId: '',
        projectDutyId: '',
        endTime: '',
        remarks: ''
      })
    }
  }
}
</script>
<style lang="less" scoped>
.center {
  text-align: center;
  display: inline-block;
  width: 100%;
}
.flex-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
/deep/ .table-striped td {
  background-color: #fafafa;
}
/deep/ .form-item  {
  .ant-input:not([disabled]),
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number:not([disabled]),
  .ant-cascader-picker {
    border-color: #e4ac0b;

    background-color: #fff9e8;
  }
  .ant-input-disabled,
  .ant-input-number-disabled .ant-input-number-input,
  .ant-time-picker-input[disabled] {
    border-color: #d9d9d9 !important;
    background-color: #f5f5f5 !important;
  }

  .remark {
    .ant-input {
      border-color: inherit !important;
      background-color: initial !important;
    }
  }
}
</style>